package gcontent.filter.site;

import java.io.ByteArrayInputStream;
import java.util.Vector;

import gcontent.filter.error.FilterEx;
import gcontent.filter.string.FilterString;
import gcontent.filter.string.StringValue;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/*
	<![CDATA[
	  			<?xml version="1.0" enconding="UTF-8" ?>
	  				<params minpercentage="50" maxpercentage="100">
	  					<site_contains>vestido</site_contains>
	  				</params>	
	  		]]>	*/
public class FilterSiteParams {

	public static void getParams(String input, FilterString filter_str)  throws FilterEx
	{
		DocumentBuilderFactory dbfactory;
		DocumentBuilder builder; 
		Document doc;
		Vector<StringValue> strings = new Vector<StringValue>();
	
		try {
			String percen_str;
			NodeList node_list;
	
			dbfactory =  DocumentBuilderFactory.newInstance();	
			builder = dbfactory. newDocumentBuilder();
			doc = builder.parse(new ByteArrayInputStream(input.getBytes()));
			
			percen_str = doc.getDocumentElement().getAttribute("minpercentage");
			
			filter_str.set_minpercentage(Integer.parseInt(percen_str));
			
			percen_str = doc.getDocumentElement().getAttribute("maxpercentage");
			filter_str.set_maxpercentage(Integer.parseInt(percen_str));
			
			node_list = doc.getDocumentElement().getChildNodes();
			for(int i = 0; node_list.item(i) != null; i++) {
				Node node;
				String node_name;
				StringValue str_value = null;
				
				node = node_list.item(i);
				node_name = node.getNodeName();

				if(node_name.equals("site_begins")) {
					str_value = new StringValue(node.getTextContent(), StringValue.STRING_BEGINS);
				} else if(node_name.equals("site_ends")) {
					str_value = new StringValue(node.getTextContent(), StringValue.STRING_ENDS);
				} else if(node_name.equals("site_contains")) {
					str_value = new StringValue(node.getTextContent(), StringValue.STRING_CONTAINS);
				} else if(node_name.equals("file_name")) {
					str_value = new StringValue(node.getTextContent(), StringValue.FILE_NAME);
				} else if(node_name.charAt(0) != '#')
					throw new FilterEx("FilterSiteParams : invalid parameter " + node_name);
				
				if(str_value != null)
					strings.add(str_value);
			}
			
		} catch(Exception ex) {
			throw new FilterEx(ex);
		}
		
		if(strings.size() == 0)
			throw new FilterEx("FilterStringParams : not strings defined!");
		
		filter_str.setStrings(strings);
	}
}
